package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.Article;
import cn.tedu._05mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Validated
@RestController
@RequestMapping("/v1/users/")
@Slf4j
@Api(tags = "01.用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("登录功能")
    @PostMapping("login")

    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("UserRegDTO = " + userLoginDTO);
        UserVO userVO = userMapper.selectUserByUser(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        System.out.println(userVO);
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        // 登录成功,将用户信息保存到session中
        session.setAttribute("user", userVO);
        return  JsonResult.ok();
    }

    @ApiOperation("发表文章功能")
    @PostMapping("article")
    public JsonResult insert(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session) {
        log.debug("UserArticleDTO = " + userArticleDTO);
        //校验登陆状态
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO, article);
        article.setUser_id(userVO.getId());
        userMapper.insertArticle(article);
        return new JsonResult(StatusCode.OPERATION_SUCCESS);//操作成功
    }

    @ApiOperation("查询指定文章功能")
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章编号必须在1-100之间") @RequestParam Integer id) {
        log.debug("id = " + id);
        ArticleVO articleVO = userMapper.selectByArticleId(id);
        return JsonResult.ok(articleVO);
    }
}
